使用語法
sqlcmd -S IP位址 -U 帳號 -P 密碼 -d 資料庫名稱 -Q 指令 -i 指令檔完整路徑
-o 輸出檔完整路徑 -s 分隔符號 -W 標題列
sqlcmd -S 127.0.0.1 -U sa -P pwd -d DBname -s"," -Q "create table mytable(col1 int)"
sqlcmd -S 127.0.0.1 -U sa -P pwd -d DBname -s"," -Q "SELECT top 10 * FROM tmp" -o E:\tmp.csv -W
將以上語法存成批次檔.bat後,執行它.
就會在E槽看到檔案tmp.csv
也可以把query存在檔案裡 -i 指令檔完整路徑sqlcmd -S 127.0.0.1 -U sa -P pwd -d DBname -s"," -i E:\test.sql -o E:\tmp.csv -W
在query 先加上 SET NOCOUNT on;sqlcmd -S 127.0.0.1 -U sa -P pwd -d DBname -s"," -Q "SET NOCOUNT on;SELECT top 10 * FROM tmp" -o E:\tmp.csv -W
REM Get the column headers
sqlcmd -S 127.0.0.1 -U sa -P sa -d dbname -s"," -Q "SET NOCOUNT on;SELECT top 10 * FROM tmp" -o "E:\20.csv"
rem Remove hyphen line
findstr /R /C:"^[^-]*$" E:\20.csv > E:\21.csv
執行 批次檔.bat
就會在E:\21.csv看到產出的檔案
處理方式
1.加' 缺:打開,如果沒有點cell的話,就會看到'sqlcmd -S 127.0.0.1 -U sa -P pwd -d DBname -s"," -Q "SET NOCOUNT on;SELECT top 10 CHAR(39) +'0001' " -o E:\tmp.csv -W
2.字串後加TAB 缺:字串後有TABsqlcmd -S 127.0.0.1 -U sa -P pwd -d DBname -s"," -Q "SET NOCOUNT on;SELECT top 10 '0001'+'' " -o E:\tmp.csv -W
使用Sqlcmd執行指令檔來匯入資料
https://dotblogs.com.tw/whd/2016/01/10/155154
設分隔-s","
https://social.msdn.microsoft.com/Forums/sqlserver/en-US/3b18fc32-b966-4de3-96a1-e237b07396f7/sqlcmd-outfile-as-tab-delimited-text-file?forum=sqltools
去除dash line
https://stackoverflow.com/questions/30452066/removing-hyphens-in-sqlcmd/30453893
bcp &sqlcmd 教學
https://www.excel-sql-server.com/sql-server-export-to-excel-using-bcp-sqlcmd-csv.htm